$(document).ready(function(){
	// 导入模块
	const api = require("../modules/api.js");
	const id = window.location.pathname.split("/product/")[1];
	let product = {};
	let type = $(".type-group .type-item").eq(0).data()["type"];
	const shopCart = {};
	shopCart.type = type;
	$(".type-group .type-item").eq(0).addClass("type-item-active");

	// 获取商品详情
	api.product_detail(id).then(data=>{
		if(data.code == "0"){
			product = data.result;
			try{
                product.discountsConfig = JSON.parse(data.result.discountsConfig);
            }catch(e){
                product.discountsConfig = [];
            };
            let initPrice = "";
            if(shopCart.type == "PF"){
            	console.log("good");
                $(".unit-price").text(product.pfPrice);
            }else if(shopCart.type == "TP"){
            	console.log("bad");
            	console.log(product.tpPrice);
                $(".unit-price").text(product.tpPrice);
            };
            shopCart.items = [{
				productName: product.name,
				productId: product.id,
				productCover: product.cover.split(",")[0],
				discountUnitPrice: 0,
				orginalUnitPrice: 0,
				quantity: 0,
				type: type
            }];
			
			console.log(shopCart);
		};
	});
	
	let is_open = false;
	// 点击下单
	$("#submit").click(function(){
		$(".modal").fadeIn();
		$(".modal .modal-content").addClass("modal-content-active");
		if(!is_open){
			is_open = true;
			return;
		};
		let quantity = shopCart.quantity;
		if(quantity_validate(quantity)){
			sessionStorage.setItem("shopCart", JSON.stringify(shopCart));
			window.location.href = "/h5/order_confirm";
		};
	});

	// 类型变化
	$(".type-group .type-item").click(function(){
		let type = $(this).data()["type"];
		shopCart.type = type;
		shopCart.items[0].type = type;
		$(".type-group .type-item").removeClass("type-item-active");
		$(this).addClass("type-item-active");
	});

	// 监测数量变化
	$("#quantity").bind("input property", function(){
		computeDiscount();
	});

	function quantity_validate(quantity){
		if(!quantity){
			$("#quantity-error").text("请填写数量！").fadeIn();
			$("#quantity").addClass("input-error");
			return false;
		};
		if(!/^[0-9]*[1-9][0-9]*$/.test(quantity)){
			$("#quantity-error").text("请填写正确的数量！").fadeIn();
			$("#quantity").addClass("input-error");
			return false;
		};
		if(quantity < product.minCount){
			$("#quantity-error").text(`数量不能少于${product.minCount}件！`).fadeIn();
			$("#quantity").addClass("input-error");
			return false;
		};
		$("#quantity-error").fadeOut();
		$("#quantity").removeClass("input-error");
		return true;
	};

	function computeDiscount(){
        var val = $("#quantity").val();
        shopCart.quantity = val;
        if(quantity_validate(val)){
            let discount = 1;
            for(let i = 0; i < product.discountsConfig.length; i ++){
                if(val <= product.discountsConfig[i].max){
                   discount = product.discountsConfig[i].discount;
                    return computeTotal(shopCart.quantity, discount);
                }else if(val >= product.discountsConfig[product.discountsConfig.length - 1].max){
                    discount = product.discountsConfig[product.discountsConfig.length - 1].discount;
                    return computeTotal(shopCart.quantity, discount);
                };
            };
        };
    };

    /*---------计算-----------*/
    function computeTotal(quantity, discount){
        console.log("discount: ", discount);
        let price = "";
        if(shopCart.type == "TP"){
            price = product.tpPrice;
        }else if(shopCart.type == "PF"){
            price = product.pfPrice;
        };
		console.log("price: ", price);
        let unit_price = (discount * price).toFixed(2);
        console.log("unit_price:", unit_price);
        $(".unit-price").text(unit_price);

        let express_price = (shopCart.quantity * product.unitFreight).toFixed(2);
        $(".unitFreight").text(express_price);
        
        let total_price = (discount * price * shopCart.quantity + shopCart.quantity * product.unitFreight).toFixed(2);
        console.log(total_price);
        $(".total-price").text(total_price);

        shopCart.items[0].quantity = quantity;
        shopCart.items[0].discountUnitPrice = unit_price;
        shopCart.orderPrice = (discount * price * shopCart.quantity).toFixed(2);
        shopCart.payPrice = total_price;
        shopCart.freight = (shopCart.quantity * product.unitFreight).toFixed(2);
    };

    $(".modal").click(function(){
		//$(".modal").fadeOut();
		$(".modal .modal-content").removeClass("modal-content-active");
		setTimeout(()=>{
			$(".modal").fadeOut()
		}, 200);
    });
    $(".modal-content").click(function(e){
		e.stopPropagation();
    });
});